package com.cn.worldex.commontask.scheduled;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cn.worldex.commontask.entity.ResponseData;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;

//@Component
//@EnableScheduling
@Slf4j
public class RdsBackUp {
    /**
     * worldex仓库正式环境备份
     */
    public void worldexIwmsBackUp() throws ClientException, IOException {
        backUp("XXXXXX","XXXXXXXX","rm-XXXX","/data/backup/worldexIwms");
        log.debug("worldex仓库系统："+LocalDateTime.now().toString()+"备份文件完成");
    }




    /**
     * @Scheduled(cron = "0 15 03 ? * * ")
      * @throws IOException
     * @throws ClientException
     */
    public void worldexBackUp() throws IOException, ClientException {
        backUp("XXX","XXXX","rm-XXX","/data/backup/worldexOA");
        log.debug("worldexOA系统："+LocalDateTime.now().toString()+"备份文件完成");
    }

    /**
     *  @Scheduled(cron = "0 0 04 ? * * ")
     */
    public void medLogBackUp() throws IOException, ClientException {
        backUp("XXX", "XXX", "rm-XXX","/data/backup/medLogOA");
        log.debug("medLogOA系统："+LocalDateTime.now().toString()+"备份文件完成");
    }


    private void backUp(String accessKeyId,String secret,String dbInstanceId,String filePath) throws ClientException, IOException {
        CommonResponse response = getResponse(accessKeyId,secret,dbInstanceId);
        String data = response.getData();
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseData responseData = objectMapper.readValue(data, ResponseData.class);
        //删除文件 ， 只备份7天
        deleteOldFile(filePath);
        //保存文件
        if(responseData != null && responseData.getItems()!=null && responseData.getItems().getBackup().size()>0){
            FileUtils.copyURLToFile(new URL(responseData.getItems().getBackup().get(0).getBackupDownloadURL()),
                    new File(filePath, LocalDate.now() +".tar.gz"));
        }
    }


    /**
     * 删除文件
     * @param dir
     * @throws IOException
     */
    private void deleteOldFile(String dir) throws IOException {
        String oldFileName = LocalDate.now().minusMonths(1)+".tar.gz";
        FileUtils.forceDeleteOnExit(new File(dir,oldFileName));
    }


    /**
     *
     * @param accessKeyId
     * @param secret
     * @param dBInstanceId
     * @return
     * @throws ClientException
     */
    private CommonResponse getResponse(String accessKeyId,String secret,String dBInstanceId) throws ClientException {
        // 创建DefaultAcsClient实例并初始化
        // 地域ID
        // RAM账号的AccessKey ID"LTAIRiymKVVcj6Vc"
        // RAM账号AccessKey Secret "CMlrRujPk8xvQj98hfQCBp2u1WOnZc"
        DefaultProfile profile = DefaultProfile.getProfile("2052",accessKeyId,secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setDomain("rds.aliyuncs.com");
        request.setMethod(MethodType.POST);
        //LocalDate.now().toString()
        request.setVersion("2014-08-15");
        //查询RDS实例的日志备份文件，包括文件的下载链接
        request.setAction("DescribeBackups");
        //实例ID"rm-uf6z400164wo7q0y4"
        request.putQueryParameter("DBInstanceId", dBInstanceId);
        request.putQueryParameter("BackupStatus","Success");
        //查询开始时间。格式：yyyy-MM-ddTHH:mmZ，例如2018-10-31T08:40Z
        request.putQueryParameter("StartTime",LocalDate.now().minusDays(7)+"T12:00Z");
        //查询结束时间。格式：yyyy-MM-ddTHH:mmZ，例如2018-10-31T08:40Z 必须晚于查询开始时间。
        request.putQueryParameter("EndTime",LocalDate.now()+"T12:00Z");
        //每页最多显示的日志文件个数。取值：30,50,100默认值：30
        request.putQueryParameter("PageSize","30");
        //页码。大于0且不超过Integer的最大值。默认值：1。
        request.putQueryParameter("PageNumber","1");
        CommonResponse response = new CommonResponse();
        response = client.getCommonResponse(request);
        return response;
    }





}
